package com.sdses.weather.config.aop;


import cn.hutool.core.util.StrUtil;
import com.sdses.weather.config.WeatherConfigRegistry;
import com.sdses.weather.config.WeatherProviderProperties;
import com.sdses.weather.config.exception.BusinessException;
import com.sdses.weather.model.RequestContext;
import com.sdses.weather.model.RequestContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class WeatherContextAspect {

    @Autowired
    private WeatherConfigRegistry configRegistry;


    @Around("execution(* com.sdses.weather.api.WeatherCommonApi.*(..))")
    public Object setRequestContext(ProceedingJoinPoint joinPoint) throws Throwable {

        HttpServletRequest request = ((ServletRequestAttributes) org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes()).getRequest();

        String provider = request.getParameter("provider");
        String cityId = request.getParameter("cityId");
        String lat = request.getParameter("lat");
        String lon = request.getParameter("lon");

        if (provider == null) {
            throw new BusinessException("缺少 provider 参数");
        }

        WeatherProviderProperties.ReqRespConfig requestURIConfigMap = null;
        //  自动推断 requestType
        if (StrUtil.isNotBlank(cityId)) {
            requestURIConfigMap = configRegistry.getRequestURIConfigMap(provider, true, request.getRequestURI());
        } else if (StrUtil.isNotBlank(lat) && StrUtil.isNotBlank(lon)) {
            requestURIConfigMap = configRegistry.getRequestURIConfigMap(provider, false, request.getRequestURI());
        }

        if (requestURIConfigMap == null) {
            throw new BusinessException("无法识别的请求类型，缺少必要参数");
        }

        RequestContext context = new RequestContext(requestURIConfigMap);
        context.setProvider(provider);
        context.setCityId(cityId);
        context.setLat(lat);
        context.setLon(lon);

        RequestContextHolder.setContext(context);
        try {
            return joinPoint.proceed();
        } finally {
            RequestContextHolder.clear();
        }
    }

}